package org.alis.smallcc.alis.tools.lock.distributed;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.DisposableBean;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class ZookeeperLockManager extends AbstrackLockManager implements DisposableBean{


    private final CuratorFramework client;
    private final ThreadPoolExecutor executor;

    private boolean mutexTaskExecutorExplicitlySet;

    public ZookeeperLockManager(CuratorFramework client) {
        if (null == client) {
            throw new NullPointerException();
        }
        executor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000),
				new ThreadFactoryBuilder().setNameFormat("zookeeper-lock-pool").build(),
				new ThreadPoolExecutor.AbortPolicy());
        this.client = client;
    }


    @Override
    public void destroy() throws Exception {
        if (!this.mutexTaskExecutorExplicitlySet) {
        	executor.shutdown();
        }
    }

    @Override
    protected Lock createLock(String lockName) {
        return new ZookeeperLock(this.client, lockName,this.executor);
    }

    @Override
    protected ReadWriteLock createReadWriteLock(String lockName) {
        return new ZookeeperReadWriteLock(this.client, lockName,this.executor);
    }

}
